<template>
  <div class="booking-page">
    <!-- 导航栏 -->
    <div class="nav-bar">
      <div class="nav-content">
        <el-icon class="back-icon" @click="goBack">
          <ArrowLeft />
        </el-icon>
        <span class="nav-title">预约看房</span>
        <div class="nav-placeholder"></div>
      </div>
    </div>
    
    <!-- 页面内容 -->
    <div class="booking-content" v-loading="isLoading">
      <!-- 有预约记录时显示列表 -->
      <div v-if="bookingList.length > 0" class="booking-list-container">
        <BookingItem
          v-for="booking in bookingList"
          :key="booking.id"
          :booking="booking"
          @click="handleBookingClick(booking)"
          @cancel="handleCancelBooking"
          @contact="handleContactBooking"
        />
      </div>
      
      <!-- 空数据状态 -->
      <div v-else-if="!isLoading" class="empty-state">
        <div class="empty-content">
          <div class="empty-image">
            <img src="@/assets/imgs/blank.png" alt="暂无预约记录" />
          </div>
          <div class="empty-text">
            <h3 class="empty-title">暂无预约记录</h3>
            <p class="empty-description">
              您还没有预约过任何房源<br>
              快去看看心仪的房源吧
            </p>
          </div>
          <div class="empty-actions">
            <el-button type="primary" @click="goToRoomList">
              去看房源
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import BookingItem from './components/BookingItem.vue'
import { getBookRentRoomListApi, cancelBookingApi } from '@/api/booking'
import { 
  bookingList, 
  isLoading, 
  setBookingList, 
  setLoading, 
  removeBooking,
  addBooking
} from '@/stores/booking'

const router = useRouter()

// 使用全局状态中的loading和bookingList
// const loading = ref(false) - 已从状态管理导入 isLoading
// const bookingList = ref([]) - 已从状态管理导入 bookingList

// 获取预约看房列表
const getBookingList = async () => {
  try {
    setLoading(true)
    const data = await getBookRentRoomListApi()
    // 根据后端接口文档，响应格式为 {code: 200, data: []}
    setBookingList(data || [])
    console.log('预约看房列表:', data)
  } catch (error) {
    console.error('获取预约看房列表失败:', error)
    ElMessage.error(error.message || '获取预约看房列表失败')
  } finally {
    setLoading(false)
  }
}

// 处理预约记录点击
const handleBookingClick = (booking) => {
  console.log('预约记录点击:', booking)
  // 跳转到房源详情页
  router.push({ name: 'RentRoomDetail', params: { id: booking.houseId } })
}

// 处理取消预约
const handleCancelBooking = async (bookingId) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消这个预约吗？',
      '取消预约',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 使用状态管理移除预约记录
    const removedBooking = removeBooking(bookingId)
    
    if (removedBooking) {
      try {
        const result = await cancelBookingApi(bookingId)
        // 根据后端接口文档，成功响应格式为 {code: 200, message: "取消成功"}
        ElMessage.success(result.message || '预约已取消')
        
        // 触发全局事件，通知其他组件预约已取消
        window.dispatchEvent(new CustomEvent('booking-cancelled', {
          detail: { bookingId }
        }))
      } catch (error) {
        // 如果API调用失败，重新添加预约记录
        addBooking({
          name: removedBooking.name || '',
          phone: removedBooking.phone || '',
          date: removedBooking.date,
          comment: removedBooking.comment,
          houseId: removedBooking.houseId
        }, {
          houseTitle: removedBooking.title,
          housePicture: removedBooking.img,
          address: removedBooking.subTitle,
          distanceInfo: removedBooking.distanceInfo,
          rentPriceListing: removedBooking.rentPrice,
          tags: removedBooking.tags
        })
        console.error('取消预约失败:', error)
        ElMessage.error(error.message || '取消预约失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消预约确认失败:', error)
    }
  }
}

// 处理联系房东
const handleContactBooking = (booking) => {
  ElMessage.info(`联系房东查看房源：${booking.title}`)
  console.log('联系房东:', booking)
}

// 跳转到房源列表
const goToRoomList = () => {
  router.push('See')
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 监听预约成功事件
const handleBookingSuccess = (event) => {
  console.log('收到预约成功事件:', event.detail)
  // 使用状态管理添加新的预约记录，而不是重新获取整个列表
  const { roomInfo, bookingInfo } = event.detail
  if (roomInfo && bookingInfo) {
    addBooking(bookingInfo, roomInfo)
  } else {
    // 如果没有详细信息，则刷新整个列表
    getBookingList()
  }
}

// 页面初始化
onMounted(() => {
  getBookingList()
  
  // 监听预约成功事件
  window.addEventListener('booking-success', handleBookingSuccess)
})

// 页面卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('booking-success', handleBookingSuccess)
})
</script>

<style scoped>
.booking-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.nav-bar {
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  height: 44px;
}

.back-icon {
  font-size: 20px;
  cursor: pointer;
  color: #333;
  transition: color 0.3s ease;
}

.back-icon:hover {
  color: #409eff;
}

.nav-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.nav-placeholder {
  width: 20px;
}

.booking-content {
  flex: 1;
  position: relative;
}

.booking-list-container {
  padding: 16px;
}

/* 空数据状态 */
.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
  padding: 40px 20px;
}

.empty-content {
  text-align: center;
  max-width: 320px;
}

.empty-image {
  margin-bottom: 24px;
}

.empty-image img {
  width: 120px;
  height: 120px;
  opacity: 0.6;
  filter: grayscale(20%);
}

.empty-text {
  margin-bottom: 24px;
}

.empty-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 12px 0;
}

.empty-description {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  margin: 0;
}

.empty-actions {
  display: flex;
  justify-content: center;
}

.empty-actions .el-button {
  min-width: 120px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .nav-content {
    padding: 8px 12px;
  }
  
  .nav-title {
    font-size: 16px;
  }
  
  .booking-list-container {
    padding: 12px;
  }
  
  .empty-state {
    min-height: 50vh;
    padding: 30px 16px;
  }
  
  .empty-content {
    max-width: 280px;
  }
  
  .empty-image img {
    width: 100px;
    height: 100px;
  }
  
  .empty-title {
    font-size: 16px;
  }
  
  .empty-description {
    font-size: 13px;
  }
}

/* Loading状态样式 */
:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.8);
}

:deep(.el-loading-spinner) {
  top: 50%;
  margin-top: -50px;
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.booking-list-container {
  animation: fadeInUp 0.5s ease;
}

.empty-content {
  animation: fadeInUp 0.5s ease;
}
</style>
